

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Blue~u~u~u">
  <meta name="author" content="Blue~u~u~u">
  <meta name="keywords" content="">
  <meta name="description" content="特定场景解决方案第一节 CountDownLatch效果：指定一个操作步骤数量，在各个子线程中，每完成一个任务就给步骤数量 - 1；在步骤数量减到0之前，CountDownLatch 可以帮我们把最后一步操作抑制住（阻塞），让最后一步操作一直等到步骤被减到 0 的时候执行。 1、班长锁门有六名同学在值日，班长负责锁门。班长必须确保所有同学都离开教室再锁门。 12345678910111213141">
<meta property="og:type" content="article">
<meta property="og:title" content="JUC学习笔记（四）特定场所解决方案">
<meta property="og:url" content="http://www.slx.blue/2022/03/10/JUC04-scenario/index.html">
<meta property="og:site_name" content="Blue~u~u~u~u">
<meta property="og:description" content="特定场景解决方案第一节 CountDownLatch效果：指定一个操作步骤数量，在各个子线程中，每完成一个任务就给步骤数量 - 1；在步骤数量减到0之前，CountDownLatch 可以帮我们把最后一步操作抑制住（阻塞），让最后一步操作一直等到步骤被减到 0 的时候执行。 1、班长锁门有六名同学在值日，班长负责锁门。班长必须确保所有同学都离开教室再锁门。 12345678910111213141">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-01.png?versionId=CAEQKRiBgMCb3bLH.xciIDI4NDZiZTZmMWM4ZTRkOWY4ZjMxYjMxOGUxNGE1Y2Fj">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-02.png?versionId=CAEQKRiCgICV3bLH.xciIGU1MDA3NDdkYTQ0YjRlODA4ZTE0YjAwMjgyMmY0MGRm">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-03.png?versionId=CAEQKRiBgICY3bLH.xciIGVlMTRiYzY5OTBjODQ2MzViY2NjOTg3NDViM2Y1MWE1">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-04.png?versionId=CAEQKRiBgICV3bLH.xciIDIxNTc3M2VjYWQyNDRmMjhhOTA2YTRiM2JmMTRkYjEz">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-05.png?versionId=CAEQKRiBgICP3bLH.xciIDc4MWNmYmY0NzhjMTQ1NGRhNjAyMDU3N2RiZTc5MThl">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-06.png?versionId=CAEQKRiBgMDX27LH.xciIDIyNmZhMzVmYmU1YzRjYTFiOTY0MmI2NjIyMDdhODU1">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-07.png?versionId=CAEQKRiBgIDP27LH.xciIDE1ZjViNWQyMzM3ZDRkMmNiMTczNzAxNGEwNGEyNWM2">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-08.png?versionId=CAEQKRiCgIDN27LH.xciIDk0YjEwM2MwMWZiNjQyMjNiNjY2MDkxZWY5YzQzYmZi">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-09.png?versionId=CAEQKRiBgIDJ27LH.xciIGYzNjg0ZmU3ODFkNDRmZmNiNTNmZDhhZjdmN2QzOWI5">
<meta property="article:published_time" content="2022-03-10T03:38:33.000Z">
<meta property="article:modified_time" content="2022-03-10T03:40:42.802Z">
<meta property="article:author" content="Blue~u~u~u">
<meta property="article:tag" content="JUC">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-01.png?versionId=CAEQKRiBgMCb3bLH.xciIDI4NDZiZTZmMWM4ZTRkOWY4ZjMxYjMxOGUxNGE1Y2Fj">
  
  <title>JUC学习笔记（四）特定场所解决方案 - Blue~u~u~u~u</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.slx.blue","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":180,"cursorChar":"_","loop":true},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>

<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
<script src="/live2d-widget/autoload.js"></script>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Blue~u~u</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="JUC学习笔记（四）特定场所解决方案">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-03-10 11:38" pubdate>
        2022年3月10日 中午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      20k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      63 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">JUC学习笔记（四）特定场所解决方案</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：3 个月前
                
              </p>
            
            <div class="markdown-body">
              <h1 id="特定场景解决方案"><a href="#特定场景解决方案" class="headerlink" title="特定场景解决方案"></a>特定场景解决方案</h1><h1 id="第一节-CountDownLatch"><a href="#第一节-CountDownLatch" class="headerlink" title="第一节 CountDownLatch"></a>第一节 CountDownLatch</h1><p>效果：指定一个操作步骤数量，在各个子线程中，每完成一个任务就给步骤数量 - 1；在步骤数量减到0之前，CountDownLatch 可以帮我们把最后一步操作抑制住（阻塞），让最后一步操作一直等到步骤被减到 0 的时候执行。</p>
<h2 id="1、班长锁门"><a href="#1、班长锁门" class="headerlink" title="1、班长锁门"></a>1、班长锁门</h2><p>有六名同学在值日，班长负责锁门。班长必须确保所有同学都离开教室再锁门。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 声明一个变量，用来保存同学的数量</span><br><span class="hljs-keyword">int</span> stuNum = <span class="hljs-number">6</span>;<br><br><span class="hljs-comment">// 创建CountDownLatch对象</span><br>CountDownLatch countDownLatch = <span class="hljs-keyword">new</span> CountDownLatch(stuNum);<br><br><span class="hljs-comment">// 创建和同学数量相等的线程</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; stuNum; i++) &#123;<br><br>    String num = String.valueOf(i + <span class="hljs-number">1</span>);<br><br>    <span class="hljs-keyword">new</span> Thread(()-&gt;&#123;<br><br>        <span class="hljs-comment">// 完成一次操作</span><br>        System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; &quot;</span> + num + <span class="hljs-string">&quot;号同学离开教室&quot;</span>);<br>        <span class="hljs-comment">// 让countDownLatch管理的数量-1</span><br>        countDownLatch.countDown();<br><br>    &#125;).start();<br><br>&#125;<br><br><span class="hljs-comment">// 让countDownLatch负责将最后一步操作抑制住</span><br>countDownLatch.await();<br><br>System.out.println(<span class="hljs-string">&quot;班长锁门&quot;</span>);<br></code></pre></td></tr></table></figure>



<h2 id="2、集齐七颗龙珠召唤神龙"><a href="#2、集齐七颗龙珠召唤神龙" class="headerlink" title="2、集齐七颗龙珠召唤神龙"></a>2、集齐七颗龙珠召唤神龙</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 声明龙珠数量</span><br><span class="hljs-keyword">int</span> dragonBall = <span class="hljs-number">7</span>;<br><br><span class="hljs-comment">// 创建CountdownLatch对象</span><br>CountDownLatch countDownLatch = <span class="hljs-keyword">new</span> CountDownLatch(dragonBall);<br><br><span class="hljs-comment">// 创建七个线程收集龙珠</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">7</span>; i++) &#123;<br>    String num = String.valueOf(i);<br>    <span class="hljs-keyword">new</span> Thread(()-&gt;&#123;<br>        System.out.println(<span class="hljs-string">&quot;现在拿到了&quot;</span> + num + <span class="hljs-string">&quot;号龙珠&quot;</span>);<br>        countDownLatch.countDown();<br>    &#125;).start();<br>&#125;<br><br><span class="hljs-comment">// 让countDownLatch对象抑制最后一步</span><br>countDownLatch.await();<br>System.out.println(<span class="hljs-string">&quot;龙珠集齐，召唤神龙&quot;</span>);<br></code></pre></td></tr></table></figure>

<h1 id="第二节-CyclicBarrier"><a href="#第二节-CyclicBarrier" class="headerlink" title="第二节 CyclicBarrier"></a>第二节 CyclicBarrier</h1><p>支持多线程在执行各自任务的时候，到达某个状态点就等待，等所有线程都到达这个状态点再继续执行后步骤。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">O19CyclicBarrierTest</span> </span>&#123;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> List&lt;List&lt;String&gt;&gt; matrix = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br><br>    <span class="hljs-keyword">static</span> &#123;<br>        matrix.add(Arrays.asList(<span class="hljs-string">&quot;normal&quot;</span>,<span class="hljs-string">&quot;special&quot;</span>,<span class="hljs-string">&quot;end&quot;</span>));<br>        matrix.add(Arrays.asList(<span class="hljs-string">&quot;normal&quot;</span>,<span class="hljs-string">&quot;normal&quot;</span>,<span class="hljs-string">&quot;special&quot;</span>,<span class="hljs-string">&quot;end&quot;</span>));<br>        matrix.add(Arrays.asList(<span class="hljs-string">&quot;normal&quot;</span>,<span class="hljs-string">&quot;normal&quot;</span>,<span class="hljs-string">&quot;normal&quot;</span>,<span class="hljs-string">&quot;special&quot;</span>,<span class="hljs-string">&quot;end&quot;</span>));<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br><br>        <span class="hljs-comment">// 1.创建CyclicBarrier对象</span><br>        CyclicBarrier barrier = <span class="hljs-keyword">new</span> CyclicBarrier(<span class="hljs-number">3</span>);<br><br>        <span class="hljs-comment">// 2.创建3个线程分别执行各自的任务</span><br>        <span class="hljs-keyword">new</span> Thread(()-&gt;&#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                List&lt;String&gt; list = matrix.get(<span class="hljs-number">0</span>);<br>                <span class="hljs-keyword">for</span> (String value : list) &#123;<br>                    TimeUnit.SECONDS.sleep(<span class="hljs-number">1</span>);<br>                    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; value = &quot;</span> + value);<br>                    <span class="hljs-keyword">if</span> (<span class="hljs-string">&quot;special&quot;</span>.equals(value)) &#123;<br>                        <span class="hljs-comment">// 遇到特殊任务标记，就让当前线程等一下</span><br>                        barrier.await();<br>                    &#125;<br>                &#125;<br>            &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>                e.printStackTrace();<br>            &#125; <span class="hljs-keyword">catch</span> (BrokenBarrierException e) &#123;<br>                e.printStackTrace();<br>            &#125;<br>        &#125;, <span class="hljs-string">&quot;thread01&quot;</span>).start();<br><br>        <span class="hljs-keyword">new</span> Thread(()-&gt;&#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                List&lt;String&gt; list = matrix.get(<span class="hljs-number">1</span>);<br>                <span class="hljs-keyword">for</span> (String value : list) &#123;<br>                    TimeUnit.SECONDS.sleep(<span class="hljs-number">1</span>);<br>                    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; value = &quot;</span> + value);<br>                    <span class="hljs-keyword">if</span> (<span class="hljs-string">&quot;special&quot;</span>.equals(value)) &#123;<br><br>                        <span class="hljs-comment">// 遇到特殊任务标记，就让当前线程等一下</span><br>                        barrier.await();<br>                    &#125;<br>                &#125;<br>            &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>                e.printStackTrace();<br>            &#125; <span class="hljs-keyword">catch</span> (BrokenBarrierException e) &#123;<br>                e.printStackTrace();<br>            &#125;<br>        &#125;, <span class="hljs-string">&quot;thread02&quot;</span>).start();<br>        <br>        <span class="hljs-keyword">new</span> Thread(()-&gt;&#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                List&lt;String&gt; list = matrix.get(<span class="hljs-number">2</span>);<br>                <span class="hljs-keyword">for</span> (String value : list) &#123;<br>                    TimeUnit.SECONDS.sleep(<span class="hljs-number">1</span>);<br>                    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; value = &quot;</span> + value);<br>                    <span class="hljs-keyword">if</span> (<span class="hljs-string">&quot;special&quot;</span>.equals(value)) &#123;<br>                        <span class="hljs-comment">// 遇到特殊任务标记，就让当前线程等一下</span><br>                        barrier.await();<br>                    &#125;<br>                &#125;<br>            &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>                e.printStackTrace();<br>            &#125; <span class="hljs-keyword">catch</span> (BrokenBarrierException e) &#123;<br>                e.printStackTrace();<br>            &#125;<br>        &#125;, <span class="hljs-string">&quot;thread03&quot;</span>).start();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>执行结果</strong></p>
<blockquote>
<p>thread02 value = normal<br>thread03 value = normal<br>thread01 value = normal<br>thread02 value = normal<br>thread01 value = special<br>thread03 value = normal<br>thread01  await<br>thread02 value = special<br>thread02 await<br>thread03 value = normal<br>thread03 value = special<br>thread03 await<br>thread01 value = end<br>thread02 value = end<br>thread03 value = end</p>
</blockquote>
<h1 id="第三节-Semaphore"><a href="#第三节-Semaphore" class="headerlink" title="第三节 Semaphore"></a>第三节 Semaphore</h1><h2 id="1、常规方式使用"><a href="#1、常规方式使用" class="headerlink" title="1、常规方式使用"></a>1、常规方式使用</h2><p>使用 Semaphore 可以帮助我们管理资源位；当某个线程申请资源时，由 Semaphore 检查这个资源是否可用；如果其他线程释放了这个资源，那么申请资源的线程就可以使用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 1、创建 Semaphore 对象，指定资源数量为 3</span><br>Semaphore semaphore = <span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">3</span>);<br><br><span class="hljs-comment">// 2、创建 10 个线程争夺这 3 个资源</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) &#123;<br><br>    <span class="hljs-keyword">new</span> Thread(() -&gt; &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 申请资源</span><br>            semaphore.acquire();<br>            <span class="hljs-comment">// 拿到资源执行操作</span><br>            System.out.println(<span class="hljs-string">&quot;【&quot;</span> + Thread.currentThread().getName() + <span class="hljs-string">&quot;】号车辆【驶入】车位&quot;</span>);<br>            TimeUnit.SECONDS.sleep(<span class="hljs-number">3</span>);<br>            System.out.println(<span class="hljs-string">&quot;【&quot;</span> + Thread.currentThread().getName() + <span class="hljs-string">&quot;】号车辆【驶出】车位&quot;</span>);<br>        &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>            e.printStackTrace();<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-comment">// 操作完成释放资源</span><br>            semaphore.release();<br>        &#125;<br>    &#125;, i + <span class="hljs-string">&quot;&quot;</span>).start();<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="2、引入超时机制"><a href="#2、引入超时机制" class="headerlink" title="2、引入超时机制"></a>2、引入超时机制</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 1、设定车位数量</span><br><span class="hljs-keyword">int</span> carPositionCount = <span class="hljs-number">3</span>;<br><br><span class="hljs-comment">// 2、创建 Semaphore 对象</span><br>Semaphore semaphore = <span class="hljs-keyword">new</span> Semaphore(carPositionCount);<br><br><span class="hljs-comment">// 3、创建 50 个线程抢车位</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">50</span>; i++) &#123;<br><br>    <span class="hljs-keyword">int</span> carNum = i;<br>    <span class="hljs-keyword">new</span> Thread(()-&gt;&#123;<br>        <span class="hljs-keyword">boolean</span> acquireResult = <span class="hljs-keyword">false</span>;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 线程开始时先申请资源，申请不到会进入等待状态</span><br>            <span class="hljs-comment">// 申请资源方式一：不见不散，等不到资源就一直等</span><br>            <span class="hljs-comment">// semaphore.acquire();</span><br><br>            <span class="hljs-comment">// 申请资源方式二：过时不候</span><br>            acquireResult = semaphore.tryAcquire(<span class="hljs-number">3</span>, TimeUnit.SECONDS);<br>            <span class="hljs-keyword">if</span> (acquireResult) &#123;<br>                <span class="hljs-comment">// 申请到资源时，线程会继续执行</span><br>                System.out.println(carNum + <span class="hljs-string">&quot;号车辆驶入车位&quot;</span>);<br>                <span class="hljs-comment">// 车辆在车位停放一段时间</span><br>                TimeUnit.SECONDS.sleep(<span class="hljs-number">2</span>);<br>                <span class="hljs-comment">// 停放完成离开车位</span><br>                System.out.println(carNum + <span class="hljs-string">&quot;号车辆驶出车位&quot;</span>);<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                System.out.println(carNum + <span class="hljs-string">&quot;号车辆放弃等待&quot;</span>);<br>            &#125;<br>        &#125;  <span class="hljs-keyword">finally</span> &#123;<br><br>            <span class="hljs-comment">// 判断当前线程释放拿到了资源</span><br>            <span class="hljs-keyword">if</span> (acquireResult) &#123;<br>                <span class="hljs-comment">// 任务执行完成释放资源</span><br>                semaphore.release();<br>            &#125;<br>        &#125;<br>    &#125;).start();<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="第四节-Fork-Join-框架"><a href="#第四节-Fork-Join-框架" class="headerlink" title="第四节 Fork Join 框架"></a>第四节 Fork Join 框架</h1><h2 id="1、介绍"><a href="#1、介绍" class="headerlink" title="1、介绍"></a>1、介绍</h2><p>使用 Fork Join 框架能够帮助我们把一个大型任务，根据一定规律，拆分成小任务执行。如果拆分后的任务还不够小，可以以<strong>递归</strong>模式继续拆分，直到拆分到可以执行的程度。然后再把各个子任务执行的结果汇总到一起。</p>
<ul>
<li>Fork：拆分：把大任务拆分成小任务。</li>
<li>Join：合并：把小任务执行的结果合并到一起。</li>
</ul>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-01.png?versionId=CAEQKRiBgMCb3bLH.xciIDI4NDZiZTZmMWM4ZTRkOWY4ZjMxYjMxOGUxNGE1Y2Fj" srcset="/img/loading.gif" lazyload alt="iamges"></p>
<h2 id="2、框架中-API-介绍"><a href="#2、框架中-API-介绍" class="headerlink" title="2、框架中 API 介绍"></a>2、框架中 API 介绍</h2><h3 id="①RecursiveTask"><a href="#①RecursiveTask" class="headerlink" title="①RecursiveTask"></a>①RecursiveTask</h3><p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-02.png?versionId=CAEQKRiCgICV3bLH.xciIGU1MDA3NDdkYTQ0YjRlODA4ZTE0YjAwMjgyMmY0MGRm" srcset="/img/loading.gif" lazyload alt="images"></p>
<p>我们使用 Fork Join 框架只需要继承 RecursiveTask，然后重写 compute() 方法即可。在 compute() 方法中需要包含：</p>
<ul>
<li>任务拆分的逻辑</li>
<li>任务拆分的操作：调用 fork() 方法</li>
<li>已拆分任务的合并：调用 join() 方法</li>
<li>子任务结果的合并：将 join() 方法的返回值合并起来</li>
</ul>
<h3 id="②ForkJoinTask"><a href="#②ForkJoinTask" class="headerlink" title="②ForkJoinTask"></a>②ForkJoinTask</h3><p>ForkJoinTask 类是 RecursiveTask 的父类。</p>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-03.png?versionId=CAEQKRiBgICY3bLH.xciIGVlMTRiYzY5OTBjODQ2MzViY2NjOTg3NDViM2Y1MWE1" srcset="/img/loading.gif" lazyload alt="images"></p>
<h2 id="3、案例"><a href="#3、案例" class="headerlink" title="3、案例"></a>3、案例</h2><h3 id="①需求"><a href="#①需求" class="headerlink" title="①需求"></a>①需求</h3><p>完成从 1~100 的累加。</p>
<h3 id="②思路"><a href="#②思路" class="headerlink" title="②思路"></a>②思路</h3><p>通过任务拆分、合并的方式来实现。拆分的逻辑是：</p>
<ul>
<li>将大范围数值累加拆分为小范围数值累加。</li>
<li>在 1~10 区间范围内执行计算。</li>
</ul>
<h3 id="③代码"><a href="#③代码" class="headerlink" title="③代码"></a>③代码</h3><h4 id="1-任务类"><a href="#1-任务类" class="headerlink" title="[1]任务类"></a>[1]任务类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTask</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">RecursiveTask</span> </span>&#123;<br><br>    <span class="hljs-comment">// 区间开始位置</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> begin;<br><br>    <span class="hljs-comment">// 区间结束位置</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> end;<br><br>    <span class="hljs-comment">// 区间调整值：要通过拆分任务将区间调整到 10 以内</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> ADJUST_VALUE = <span class="hljs-number">10</span>;<br><br>    <span class="hljs-comment">// 保存当前任务的结果</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> result = <span class="hljs-number">0</span>;<br><br>    <span class="hljs-comment">// 声明构造器，设定当前任务的开始和结束位置</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyTask</span><span class="hljs-params">(<span class="hljs-keyword">int</span> begin, <span class="hljs-keyword">int</span> end)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.begin = begin;<br>        <span class="hljs-keyword">this</span>.end = end;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> Object <span class="hljs-title">compute</span><span class="hljs-params">()</span> </span>&#123;<br><br>        <span class="hljs-comment">// 1、判断当前区间是否是原子任务中可以执行计算的范围</span><br>        <span class="hljs-keyword">if</span> (end - begin &lt;= ADJUST_VALUE) &#123;<br><br>            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = begin; i &lt;= end ; i++) &#123;<br>                result  = result + i;<br>            &#125;<br><br>        &#125; <span class="hljs-keyword">else</span> &#123;<br><br>            <span class="hljs-comment">// 2、计算新拆分任务的区间范围</span><br>            <span class="hljs-keyword">int</span> leftBegin = begin;<br>            <span class="hljs-keyword">int</span> leftEnd = (begin + end) / <span class="hljs-number">2</span>;<br><br>            <span class="hljs-keyword">int</span> rightBegin = leftEnd + <span class="hljs-number">1</span>;<br>            <span class="hljs-keyword">int</span> rightEnd = end;<br><br>            <span class="hljs-comment">// 3、创建两个新的任务（子任务）</span><br>            MyTask myTaskLeft = <span class="hljs-keyword">new</span> MyTask(leftBegin, leftEnd);<br>            MyTask myTaskRight = <span class="hljs-keyword">new</span> MyTask(rightBegin, rightEnd);<br><br>            <span class="hljs-comment">// 4、调用框架提供的 fork() 进一步拆分任务</span><br>            myTaskLeft.fork();<br>            myTaskRight.fork();<br><br>            <span class="hljs-comment">// 5、调用框架提供的 join() 获取子任务计算的结果</span><br>            <span class="hljs-keyword">int</span> leftResult = (<span class="hljs-keyword">int</span>) myTaskLeft.join();<br>            <span class="hljs-keyword">int</span> rightResult = (<span class="hljs-keyword">int</span>) myTaskRight.join();<br><br>            <span class="hljs-comment">// 6、把子任务的结果合并到一起</span><br>            result = leftResult + rightResult;<br>        &#125;<br><br>        <span class="hljs-keyword">return</span> result;<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="2-测试代码"><a href="#2-测试代码" class="headerlink" title="[2]测试代码"></a>[2]测试代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 1、创建 Fork Join 任务池</span><br>ForkJoinPool pool = <span class="hljs-keyword">new</span> ForkJoinPool();<br><br><span class="hljs-comment">// 2、创建任务对象</span><br>MyTask myTask = <span class="hljs-keyword">new</span> MyTask(<span class="hljs-number">1</span>, <span class="hljs-number">100</span>);<br><br><span class="hljs-comment">// 3、将任务对象提交到任务池</span><br>ForkJoinTask forkJoinTask = pool.submit(myTask);<br><br><span class="hljs-comment">// 4、获取任务执行结果</span><br><span class="hljs-keyword">int</span> finalResult = (<span class="hljs-keyword">int</span>) forkJoinTask.get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>

<h1 id="第五节-CompletableFuture"><a href="#第五节-CompletableFuture" class="headerlink" title="第五节 CompletableFuture"></a>第五节 CompletableFuture</h1><h2 id="1、简介"><a href="#1、简介" class="headerlink" title="1、简介"></a>1、简介</h2><p>简单来说，CompletableFuture 就是 Callable + FutureTask 组合的『<strong>超级强化版</strong>』。</p>
<p>FutureTask 的核心接口 Futrue 通常用来表示一个异步任务的引用，比如我们将任务提交到线程池里面，然后我们会得到一个 Futrue 对象。在 Future 里面有 isDone() 方法来判断任务是否处理结束，还有 get() 方法可以一直阻塞直到任务结束然后获取结果。但整体来说这种方式，还是<strong>同步</strong>的，因为需要客户端不断阻塞等待或者不断轮询才能知道任务是否完成。</p>
<p>TIP</p>
<p>Future 的主要缺点如下：</p>
<ul>
<li>不支持手动完成</li>
</ul>
<p>我提交了一个任务，但是执行太慢了，我通过其他路径已经获取到了任务结果，现在没法把这个任务结果通知到正在执行的线程，所以必须主动取消或者一直等待它执行完成</p>
<ul>
<li>不支持进一步的非阻塞调用</li>
</ul>
<p>通过Future的get方法会一直阻塞到任务完成，但是想在获取任务之后执行额外的任务，因为Future不支持回调函数，所以无法实现这个功能</p>
<ul>
<li>不支持链式调用</li>
</ul>
<p>对于 Future 的执行结果，我们想继续传到下一个 Future 处理使用，从而形成一个链式的 pipeline 调用，这在Future 中是没法实现的。</p>
<ul>
<li>不支持多个 Future 合并</li>
</ul>
<p>比如我们有 10 个 Future 并行执行，我们想在所有的Future运行完毕之后，执行某些函数，是没法通过 Future 实现的。</p>
<ul>
<li>不支持异常处理</li>
</ul>
<p>Future 的 API 没有任何的异常处理的 api，所以在异步运行时，如果出了问题是不好定位的。</p>
<h2 id="2、用法"><a href="#2、用法" class="headerlink" title="2、用法"></a>2、用法</h2><ul>
<li>先调静态方法：既封装线程任务，又返回 CompletableFuture 对象。</li>
<li>通过 CompletableFuture 对象调用非静态方法：对任务进行进一步处理。</li>
</ul>
<h2 id="3、静态方法"><a href="#3、静态方法" class="headerlink" title="3、静态方法"></a>3、静态方法</h2><h3 id="①无返回值的异步任务"><a href="#①无返回值的异步任务" class="headerlink" title="①无返回值的异步任务"></a>①无返回值的异步任务</h3><p>方法名：runAsync()</p>
<p>封装任务的线程接口：Runnable 接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 1、调用 CompletableFuture 类的静态方法</span><br><span class="hljs-comment">// 目标1：封装线程内要执行的任务</span><br><span class="hljs-comment">// 目标2：返回 CompletableFuture 对象</span><br><span class="hljs-comment">// CompletableFuture&lt;泛型&gt;说明：泛型类型是用来表示线程执行任务的返回值的类型；</span><br><span class="hljs-comment">// 现在这个任务没有返回值，所以使用了 Void。</span><br>CompletableFuture&lt;Void&gt; future = CompletableFuture.runAsync(() -&gt; &#123;<br>    <span class="hljs-comment">//封装需要在线程中执行的任务</span><br>    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; working&quot;</span>);<br>&#125;);<br><br><span class="hljs-comment">// 2、调用 CompletableFuture 对象的 get() 方法</span><br><span class="hljs-comment">// 目标1：启动 CompletableFuture 对象封装任务的线程</span><br><span class="hljs-comment">// 目标2：获取当前任务执行的结果</span><br>Void taskResult = future.get();<br>System.out.println(<span class="hljs-string">&quot;taskResult = &quot;</span> + taskResult);<br></code></pre></td></tr></table></figure>



<h3 id="②有返回值的异步任务"><a href="#②有返回值的异步任务" class="headerlink" title="②有返回值的异步任务"></a>②有返回值的异步任务</h3><p>方法名：supplyAsync()</p>
<p>封装任务的线程接口：Supplier 接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 对 CompletableFuture 类以及方法返回值进行链式调用：</span><br><span class="hljs-comment">// 目标1：将线程任务封装到 Supplier 对象中。</span><br><span class="hljs-comment">// 目标2：启动封装指定任务的线程</span><br><span class="hljs-comment">// 目标3：获取线程执行任务后返回的结果</span><br>String currentTaskComputeResult =<br>        CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>            <span class="hljs-comment">//封装需要在线程中执行的任务</span><br>             System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; working&quot;</span>);<br>            <br>            <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;current thread compute result&quot;</span>;<br>        &#125;).get();<br><br>System.out.println(<span class="hljs-string">&quot;currentTaskComputeResult = &quot;</span> + currentTaskComputeResult);<br></code></pre></td></tr></table></figure>



<p>TIP</p>
<p>链式调用是如何实现的？</p>
<p>一个方法希望实现链式调用，那么只需要让这个方法的返回值是可以调用下一个方法的对象即可；</p>
<ul>
<li>静态方法：创建一个调用后面方法的对象，返回这个对象。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">static</span> &lt;U&gt; <span class="hljs-function">CompletableFuture&lt;U&gt; <span class="hljs-title">asyncSupplyStage</span><span class="hljs-params">(Executor e,</span></span><br><span class="hljs-params"><span class="hljs-function">                                                 Supplier&lt;U&gt; f)</span> </span>&#123;<br>    <span class="hljs-keyword">if</span> (f == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NullPointerException();<br>    CompletableFuture&lt;U&gt; d = <span class="hljs-keyword">new</span> CompletableFuture&lt;U&gt;();<br>    e.execute(<span class="hljs-keyword">new</span> AsyncSupply&lt;U&gt;(d, f));<br>    <span class="hljs-keyword">return</span> d;<br>&#125;<br></code></pre></td></tr></table></figure>



<ul>
<li>非静态方法：返回 this 即可</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> AbstractStringBuilder <span class="hljs-title">append</span><span class="hljs-params">(String str)</span> </span>&#123;<br>    <span class="hljs-keyword">if</span> (str == <span class="hljs-keyword">null</span>)<br>        <span class="hljs-keyword">return</span> appendNull();<br>    <span class="hljs-keyword">int</span> len = str.length();<br>    ensureCapacityInternal(count + len);<br>    str.getChars(<span class="hljs-number">0</span>, len, value, count);<br>    count += len;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="③同步多个任务"><a href="#③同步多个任务" class="headerlink" title="③同步多个任务"></a>③同步多个任务</h3><h4 id="1-allOf-方法"><a href="#1-allOf-方法" class="headerlink" title="[1]allOf() 方法"></a>[1]allOf() 方法</h4><ul>
<li>调用 allOf 方法后返回一个 CompletableFuture 对象，调用这个对象的 get() 方法能够启动汇总的各个任务的线程</li>
<li>所有具体任务线程结束后，get() 方法结束阻塞，但是不返回任何结果。</li>
<li>如果需要各个具体任务各自的结果，那就调用各自的 get() 方法</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future01 = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;任务 1 开始&quot;</span>);<br>    <span class="hljs-keyword">try</span> &#123;<br>        TimeUnit.SECONDS.sleep(<span class="hljs-number">1</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br>    System.out.println(<span class="hljs-string">&quot;任务 1 结束&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task01 result&quot;</span>;<br>&#125;);<br><br>CompletableFuture&lt;String&gt; future02 = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;任务 2 开始&quot;</span>);<br>    <span class="hljs-keyword">try</span> &#123;<br>        TimeUnit.SECONDS.sleep(<span class="hljs-number">2</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br>    System.out.println(<span class="hljs-string">&quot;任务 2 结束&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task02 result&quot;</span>;<br>&#125;);<br><br>CompletableFuture&lt;String&gt; future03 = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;任务 3 开始&quot;</span>);<br>    <span class="hljs-keyword">try</span> &#123;<br>        TimeUnit.SECONDS.sleep(<span class="hljs-number">3</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br>    System.out.println(<span class="hljs-string">&quot;任务 3 结束&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task03 result&quot;</span>;<br>&#125;);<br><br><span class="hljs-comment">// allOf 方法用来汇总各个任务</span><br>CompletableFuture&lt;Void&gt; future = CompletableFuture.allOf(future01, future02, future03);<br><br><span class="hljs-comment">// 调用 allOf 方法后返回一个 CompletableFuture 对象，调用这个对象的 get() 方法能够启动汇总的各个任务的线程</span><br>System.out.println(<span class="hljs-string">&quot;all of future 的 get() 方法开始&quot;</span>);<br><br><span class="hljs-comment">// 所有具体任务线程结束后，get() 方法结束阻塞，但是不返回任何结果。</span><br>Void nullResult = future.get();<br>System.out.println(<span class="hljs-string">&quot;all of future 的 get() 方法结束&quot;</span>);<br><br>System.out.println(<span class="hljs-string">&quot;nullResult = &quot;</span> + nullResult);<br><br><span class="hljs-comment">// 如果需要各个具体任务各自的结果，那就调用各自的 get() 方法</span><br>String task01Result = future01.get();<br>System.out.println(<span class="hljs-string">&quot;task01Result = &quot;</span> + task01Result);<br><br>String task02Result = future02.get();<br>System.out.println(<span class="hljs-string">&quot;task02Result = &quot;</span> + task02Result);<br><br>String task03Result = future03.get();<br>System.out.println(<span class="hljs-string">&quot;task03Result = &quot;</span> + task03Result);<br></code></pre></td></tr></table></figure>



<h4 id="2-anyOf-方法"><a href="#2-anyOf-方法" class="headerlink" title="[2]anyOf() 方法"></a>[2]anyOf() 方法</h4><ul>
<li>汇总各个具体任务</li>
<li>在各个具体任务中有任何一个返回，汇总得到的 future 对象的 get() 方法就会返回</li>
<li>而且返回的是当前完成的任务的返回值</li>
<li>其它没有完成的任务不再继续执行</li>
<li>如果想要其它任务的结果，需要调用其它任务的 get() 方法，此时没有完成的任务会继续执行</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future01 = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;任务 1 开始&quot;</span>);<br>    <span class="hljs-keyword">try</span> &#123;<br>        TimeUnit.SECONDS.sleep(<span class="hljs-number">1</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br>    System.out.println(<span class="hljs-string">&quot;任务 1 结束&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task01 result&quot;</span>;<br>&#125;);<br><br>CompletableFuture&lt;String&gt; future02 = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;任务 2 开始&quot;</span>);<br>    <span class="hljs-keyword">try</span> &#123;<br>        TimeUnit.SECONDS.sleep(<span class="hljs-number">2</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br>    System.out.println(<span class="hljs-string">&quot;任务 2 结束&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task02 result&quot;</span>;<br>&#125;);<br><br>CompletableFuture&lt;String&gt; future03 = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;任务 3 开始&quot;</span>);<br>    <span class="hljs-keyword">try</span> &#123;<br>        TimeUnit.SECONDS.sleep(<span class="hljs-number">3</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br>    System.out.println(<span class="hljs-string">&quot;任务 3 结束&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task03 result&quot;</span>;<br>&#125;);<br><br><span class="hljs-comment">// 汇总各个具体任务</span><br>CompletableFuture&lt;Object&gt; future = CompletableFuture.anyOf(future01, future02, future03);<br><br>System.out.println(<span class="hljs-string">&quot;总的 get() 方法开始了&quot;</span>);<br><span class="hljs-comment">// 在各个具体任务中有任何一个返回，汇总得到的 future 对象的 get() 方法就会返回</span><br><span class="hljs-comment">// 而且返回的是当前完成的任务的返回值</span><br><span class="hljs-comment">// 其它没有完成的任务不再继续执行</span><br>Object summaryResult = future.get();<br>System.out.println(<span class="hljs-string">&quot;总的 get() 方法结束了&quot;</span>);<br><br>System.out.println(<span class="hljs-string">&quot;summaryResult = &quot;</span> + summaryResult);<br><br><span class="hljs-comment">// 如果想要其它任务的结果，需要调用其它任务的 get() 方法</span><br>String task01Result = future01.get();<br>System.out.println(<span class="hljs-string">&quot;task01Result = &quot;</span> + task01Result);<br><br>String task02Result = future02.get();<br>System.out.println(<span class="hljs-string">&quot;task02Result = &quot;</span> + task02Result);<br><br>String task03Result = future03.get();<br>System.out.println(<span class="hljs-string">&quot;task03Result = &quot;</span> + task03Result);<br></code></pre></td></tr></table></figure>



<h2 id="4、非静态方法"><a href="#4、非静态方法" class="headerlink" title="4、非静态方法"></a>4、非静态方法</h2><h3 id="①获取任务线程结果-get"><a href="#①获取任务线程结果-get" class="headerlink" title="①获取任务线程结果 get()"></a>①获取任务线程结果 get()</h3><ul>
<li>显式功能：获取任务线程执行的结果，对于没有返回值的线程会返回 null。</li>
<li>隐式功能：启动任务线程。如果只是封装了任务，但是没有调用 get() 方法，那么任务线程不会被启动。</li>
<li>特点：在线程内的任务还没有完成的时候，get() 方法会一直阻塞，直到任务完成。</li>
</ul>
<h3 id="②后续操作-thenRun"><a href="#②后续操作-thenRun" class="headerlink" title="②后续操作 thenRun()"></a>②后续操作 thenRun()</h3><p>在上一个任务之后，单纯的执行下一个任务。不涉及数据传递，也没有返回值。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java">Void finalResult = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;上一个任务 &quot;</span> + Thread.currentThread().getName());<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;prev task result&quot;</span>;<br>&#125;)<br>        <span class="hljs-comment">// 在上一个任务之后，单纯的执行下一个任务。不涉及数据传递，也没有返回值。</span><br>        .thenRun(() -&gt; &#123;<br>    System.out.println(<span class="hljs-string">&quot;then run 执行当前任务 &quot;</span> + Thread.currentThread().getName());<br>&#125;).get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>



<h3 id="③消费处理结果-thenAccept"><a href="#③消费处理结果-thenAccept" class="headerlink" title="③消费处理结果 thenAccept()"></a>③消费处理结果 thenAccept()</h3><p>能够接收上一个任务的结果，但是不返回新的结果。所涉及到的泛型类型分析如下：</p>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-04.png?versionId=CAEQKRiBgICV3bLH.xciIDIxNTc3M2VjYWQyNDRmMjhhOTA2YTRiM2JmMTRkYjEz" srcset="/img/loading.gif" lazyload alt="images"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture.supplyAsync(()-&gt;&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;prev task result&quot;</span>;<br>&#125;)<br>        <span class="hljs-comment">// 消费上一个任务的结果：接收上一个任务的结果，但是当前任务没有返回值</span><br>        .thenAccept((String prevTaskResult)-&gt;&#123;<br>    System.out.println(<span class="hljs-string">&quot;prevTaskResult = &quot;</span> + prevTaskResult);<br>&#125;).get();<br></code></pre></td></tr></table></figure>



<h3 id="④线程依赖-thenApply"><a href="#④线程依赖-thenApply" class="headerlink" title="④线程依赖 thenApply()"></a>④线程依赖 thenApply()</h3><h4 id="1-Function-接口中泛型-T-的含义"><a href="#1-Function-接口中泛型-T-的含义" class="headerlink" title="[1]Function 接口中泛型 T 的含义"></a>[1]Function 接口中泛型 T 的含义</h4><p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-05.png?versionId=CAEQKRiBgICP3bLH.xciIDc4MWNmYmY0NzhjMTQ1NGRhNjAyMDU3N2RiZTc5MThl" srcset="/img/loading.gif" lazyload alt="images"></p>
<h4 id="2-Function-接口中泛型-U-的含义"><a href="#2-Function-接口中泛型-U-的含义" class="headerlink" title="[2]Function 接口中泛型 U 的含义"></a>[2]Function 接口中泛型 U 的含义</h4><p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-06.png?versionId=CAEQKRiBgMDX27LH.xciIDIyNmZhMzVmYmU1YzRjYTFiOTY0MmI2NjIyMDdhODU1" srcset="/img/loading.gif" lazyload alt="images"></p>
<h4 id="3-thenApply-方法的作用"><a href="#3-thenApply-方法的作用" class="headerlink" title="[3]thenApply() 方法的作用"></a>[3]thenApply() 方法的作用</h4><p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-07.png?versionId=CAEQKRiBgIDP27LH.xciIDE1ZjViNWQyMzM3ZDRkMmNiMTczNzAxNGEwNGEyNWM2" srcset="/img/loading.gif" lazyload alt="images"></p>
<h4 id="4-示例代码"><a href="#4-示例代码" class="headerlink" title="[4]示例代码"></a>[4]示例代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java">Integer finalTaskResult = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; 上一个任务&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;prev task result&quot;</span>;<br>&#125;).thenApply((String prevTaskResult) -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;上一个任务的返回值：&quot;</span> + prevTaskResult);<br><br>    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; 当前任务&quot;</span>);<br><br>    <span class="hljs-comment">// 返回当前任务的返回值</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">100</span>);<br>&#125;).get();<br><br>System.out.println(<span class="hljs-string">&quot;最终任务的返回值 = &quot;</span> + finalTaskResult);<br></code></pre></td></tr></table></figure>



<h4 id="5-用法说明"><a href="#5-用法说明" class="headerlink" title="[5]用法说明"></a>[5]用法说明</h4><ul>
<li>调用 thenApply() 方法需要传入 java.util.function.Function&lt;T,R&gt; 类型的对象。</li>
<li>java.util.function.Function&lt;T,R&gt; 类型的对象可以通过 Lambda 表达式来创建。</li>
<li>泛型 T：上一个任务执行的结果的数据类型。</li>
<li>泛型 R：当前 thenApply() 方法封装的任务执行的结果的数据类型。</li>
<li>从 T 和 R 是两个不同类型可以看出：前一个任务和后一个任务可以返回不同数据类型的结果。</li>
<li>在 thenApply() 方法后面调用 get() 方法可以启动线程执行已封装的所有任务。</li>
</ul>
<h4 id="6-扩展：thenApplyAsync-方法"><a href="#6-扩展：thenApplyAsync-方法" class="headerlink" title="[6]扩展：thenApplyAsync() 方法"></a>[6]扩展：thenApplyAsync() 方法</h4><ul>
<li>示例代码：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java">String finalResult = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; 上一个任务&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;prev task result&quot;</span>;<br>&#125;).thenApplyAsync((String t) -&gt; &#123;<br><br>    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; 当前任务&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;current task result&quot;</span>;<br>&#125;).get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>



<ul>
<li>运行结果：</li>
</ul>
<blockquote>
<p>ForkJoinPool.commonPool-worker-1 上一个任务 ForkJoinPool.commonPool-worker-1 当前任务 finalResult = current task result</p>
</blockquote>
<ul>
<li>说明：<ul>
<li>thenApply()：回到上一个任务所在线程的父线程执行；站在父线程的角度来看这里封装的新任务是在同一个线程（父线程）中执行的，所以算是同步的模式。</li>
<li>thenApply<strong>Async</strong>()：还在上一个任务所在的线程中执行；站在父线程的角度来看这里封装的新任务是在子线程中执行的，所以算是异步模式。</li>
</ul>
</li>
</ul>
<h3 id="⑤异常处理-exceptionally"><a href="#⑤异常处理-exceptionally" class="headerlink" title="⑤异常处理 exceptionally()"></a>⑤异常处理 exceptionally()</h3><ul>
<li>作用：针对前面的所有任务，提供异常处理的功能。</li>
<li>特点：<ul>
<li>能够接收前面任务执行过程中抛出的异常对象</li>
<li>能够在前面任务抛出异常后返回一个相同类型的备用结果，让上层程序可以继续执行（类似于 SpringCloud 中服务降级、熔断思想。）</li>
</ul>
</li>
</ul>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-08.png?versionId=CAEQKRiCgIDN27LH.xciIDk0YjEwM2MwMWZiNjQyMjNiNjY2MDkxZWY5YzQzYmZi" srcset="/img/loading.gif" lazyload alt="images"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs java">String finalResult = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    System.out.println(<span class="hljs-string">&quot;第一个任务&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;first task result&quot;</span>;<br>&#125;).thenApply((String prevTaskResult) -&gt; &#123;<br>    System.out.println(<span class="hljs-string">&quot;第二个任务 &quot;</span> + (<span class="hljs-number">10</span> / <span class="hljs-number">0</span>));<br><br>    <span class="hljs-keyword">return</span> prevTaskResult;<br>&#125;)<br>        <span class="hljs-comment">// 针对前面所有任务提供异常处理的功能</span><br>        <span class="hljs-comment">// 需要传入的对象：Function&lt;Throwable, ? extends T&gt; fn 类型</span><br>        .exceptionally((Throwable t) -&gt; &#123;<br><br>            String exceptionFullName = t.getClass().getName();<br>            System.out.println(<span class="hljs-string">&quot;exceptionFullName = &quot;</span> + exceptionFullName);<br><br>            Throwable cause = t.getCause();<br>            System.out.println(<span class="hljs-string">&quot;cause.getClass().getName() = &quot;</span> + cause.getClass().getName());<br><br>            String message = t.getMessage();<br>            System.out.println(<span class="hljs-string">&quot;message = &quot;</span> + message);<br><br>            <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;前面任务抛出了异常，由 exceptionally() 方法提供一个备选任务结果。&quot;</span>;<br>        &#125;).get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>



<h3 id="⑥结果合并：thenCompose"><a href="#⑥结果合并：thenCompose" class="headerlink" title="⑥结果合并：thenCompose()"></a>⑥结果合并：thenCompose()</h3><ul>
<li>合并两个任务</li>
<li>合并的两个任务可以传递任务结果：将第一个任务的结果传给第二个任务</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs java">String finalResult = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;first task result&quot;</span>;<br>&#125;)<br><br>        <span class="hljs-comment">// 将两个任务合并。</span><br>        <span class="hljs-comment">// 第二个任务可以接收上一个任务的结果</span><br>        .thenCompose((String prevTaskResult) -&gt; &#123;<br><br>            <span class="hljs-comment">// 封装任务的方法返回值：要求返回一个新的 CompletableFuture 对象，</span><br>            <span class="hljs-comment">// 在这个新的对象中封装第二个任务并执行任务结果的合并</span><br>            <span class="hljs-keyword">return</span> CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>                <span class="hljs-comment">// 当前任务执行的结果</span><br>                String currentTaskResult = <span class="hljs-string">&quot;second task result&quot;</span>;<br><br>                <span class="hljs-comment">// 将两个任务的结果合并</span><br>                String composedTaskResult = prevTaskResult + <span class="hljs-string">&quot;@&quot;</span> + currentTaskResult;<br><br>                <span class="hljs-keyword">return</span> composedTaskResult;<br>            &#125;);<br>        &#125;)<br>        <br>        <span class="hljs-comment">// 如果需要继续合并更多任务，那么就继续调用 thenCompose() 方法</span><br>        .thenCompose((String prevTaskResult) -&gt; &#123;<br>            <span class="hljs-keyword">return</span> CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>                <span class="hljs-comment">// 当前任务执行的结果</span><br>                String currentTaskResult = <span class="hljs-string">&quot;third task result&quot;</span>;<br><br>                <span class="hljs-comment">// 将两个任务的结果合并</span><br>                String composedTaskResult = prevTaskResult + <span class="hljs-string">&quot;@&quot;</span> + currentTaskResult;<br><br>                <span class="hljs-keyword">return</span> composedTaskResult;<br>            &#125;);<br>        &#125;).get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>



<h3 id="⑦结果合并：thenCombine"><a href="#⑦结果合并：thenCombine" class="headerlink" title="⑦结果合并：thenCombine"></a>⑦结果合并：thenCombine</h3><p>作用：组合两个任务，这两个任务之间不传递数据。但是通过 BiFunction 接口类型的对象将两个任务的结果合并到一起。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future01 = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; 第一个任务。&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;first task result&quot;</span>;<br>&#125;);<br><br>CompletableFuture&lt;String&gt; future02 = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; 第二个任务。&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;second task result&quot;</span>;<br>&#125;);<br><br>CompletableFuture&lt;String&gt; futureCombined =<br><br>        <span class="hljs-comment">// 合并前面两个任务，通过 BiFunction 接口类型的对象接收两个任务的返回值</span><br>        future01.thenCombine(future02, (String firstTaskResult, String secondTaskResult) -&gt; &#123;<br><br>    String finalResult = firstTaskResult + <span class="hljs-string">&quot; @ &quot;</span> + secondTaskResult;<br><br>    <span class="hljs-keyword">return</span> finalResult;<br>&#125;);<br><br>String finalResult = futureCombined.get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>



<p>两种合并方式对比：</p>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JUC/JUC04-09.png?versionId=CAEQKRiBgIDJ27LH.xciIGYzNjg0ZmU3ODFkNDRmZmNiNTNmZDhhZjdmN2QzOWI5" srcset="/img/loading.gif" lazyload alt="images"></p>
<h3 id="⑧手动完成任务：complete"><a href="#⑧手动完成任务：complete" class="headerlink" title="⑧手动完成任务：complete()"></a>⑧手动完成任务：complete()</h3><p>作用：如果我们能够在负责具体任务的线程返回计算结果之前，能够在别的地方拿到任务结果，那么就可以调用 complete() 方法提前结束任务。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future = CompletableFuture.supplyAsync(() -&gt; &#123;<br>     <span class="hljs-keyword">try</span> &#123;<br>         TimeUnit.SECONDS.sleep(<span class="hljs-number">10</span>);<br>     &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>     &#125;<br>     <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;normal task result&quot;</span>;<br> &#125;);<br><br> <span class="hljs-keyword">try</span> &#123;<br>     TimeUnit.SECONDS.sleep(<span class="hljs-number">3</span>);<br> &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br> &#125;<br> <span class="hljs-comment">//如果在任务之外提前拿到了任务执行的结果，可以使用这个结果提前结束任务</span><br> <span class="hljs-comment">// 提前结束任务 返回值类型必须和原类型一直，类似spring Cloud 中 服务熔断，降级思想</span><br> future.complete(<span class="hljs-string">&quot;special task result&quot;</span>);<br><br> <span class="hljs-comment">//获取最终结果</span><br> String s = future.get();<br> System.out.println(s);<br></code></pre></td></tr></table></figure>



<h3 id="⑨最后的处理：handle"><a href="#⑨最后的处理：handle" class="headerlink" title="⑨最后的处理：handle()"></a>⑨最后的处理：handle()</h3><p>相当于在处理整个任务的过程中，在最后的环节做最后的处理。 如果前面的操作中有抛出异常，那么从 Throwable throwable 参数这里可以传进来 如果前面的操作没有抛异常，那么 Throwable throwable 参数传入的就是 null</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java">String finalResult = CompletableFuture.supplyAsync(() -&gt; &#123;<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task result 0001&quot;</span>;<br>&#125;).thenApply((String prevTaskResult) -&gt; &#123;<br>    System.out.println(<span class="hljs-string">&quot;在第二个任务中获取到的上一个任务的结果 = &quot;</span> + prevTaskResult);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task result 0002&quot;</span>;<br>&#125;)<br>        <br>        <span class="hljs-comment">// 相当于在处理整个任务的过程中，在最后的环节做最后的处理。</span><br>        <span class="hljs-comment">// 如果前面的操作中有抛出异常，那么从 Throwable throwable 参数这里可以传进来</span><br>        <span class="hljs-comment">// 如果前面的操作没有抛异常，那么 Throwable throwable 参数传入的就是 null</span><br>        .handle((String prevTaskResult, Throwable throwable) -&gt; &#123;<br><br>    System.out.println(<span class="hljs-string">&quot;handle 方法中获取到的上一个任务的结果 = &quot;</span> + prevTaskResult);<br><br>    System.out.println(<span class="hljs-string">&quot;handle 方法中获取到的异常：throwable = &quot;</span> + throwable);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;current task result&quot;</span>;<br>&#125;).get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>



<h2 id="5、典型应用"><a href="#5、典型应用" class="headerlink" title="5、典型应用"></a>5、典型应用</h2><p>从其他渠道获取到计算结果后，get() 方法结束阻塞。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future = CompletableFuture.supplyAsync(()-&gt;&#123;<br><br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">20</span>; i++) &#123;<br>        System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot; is working&quot;</span>);<br>        <span class="hljs-keyword">try</span> &#123;TimeUnit.SECONDS.sleep(<span class="hljs-number">1</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br>    &#125;<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;original result&quot;</span>;<br>&#125;);<br><br><span class="hljs-keyword">new</span> Thread(()-&gt;&#123;<br><br>    <span class="hljs-keyword">try</span> &#123;TimeUnit.SECONDS.sleep(<span class="hljs-number">5</span>);&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;&#125;<br><br>    <span class="hljs-comment">// 在另一个线程中结束执行任务的原本那个线程</span><br>    <span class="hljs-keyword">boolean</span> finishResult = future.complete(<span class="hljs-string">&quot;new result from another way&quot;</span>);<br><br>    System.out.println(<span class="hljs-string">&quot;finishResult = &quot;</span> + finishResult);<br><br>&#125;).start();<br><br>String finalResult = future.get();<br><br>System.out.println(<span class="hljs-string">&quot;finalResult = &quot;</span> + finalResult);<br></code></pre></td></tr></table></figure>



<h2 id="6、电商项目"><a href="#6、电商项目" class="headerlink" title="6、电商项目"></a>6、电商项目</h2><p>异步编排的功能需要用到 CompletableFuture 这个类。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/JUC/">JUC</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/JUC/">JUC</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客目前大部分文章都是参考尚硅谷或者马士兵教育的学习资料！<a href="http://www.atguigu.com/" rel="nofollow noopener"官网地址！</a> 
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/10/JUC05-LockPrinciple/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JUC学习笔记（五）Lock底层原理探究</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/03/08/JUC03-LockApi/">
                        <span class="hidden-mobile">JUC学习笔记（三）Lock API控制多线程</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">

  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
	<!--《添加网站运行时间 -->
<br/>

<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
var now = new Date(); 

function createtime() {
    //此处修改你的建站时间或者网站上线时间
    var grt = new Date('11/02/2021 21:39:00');
    now.setTime(now.getTime() + 250);
    days = (now - grt) / 1000 / 60 / 60 / 24;

    dnum = Math.floor(days);
    hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
    hnum = Math.floor(hours);
    if (String(hnum).length == 1) {
        hnum = "0" + hnum;
    }
    minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes);
    if (String(mnum).length == 1) {
        mnum = "0" + mnum;
    }
    seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds);
    if (String(snum).length == 1) {
        snum = "0" + snum;
    }
    document.getElementById("timeDate").innerHTML = " 本站已各种夹缝中安全运行 " + dnum + " 天 ";
    document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
}
setInterval("createtime()", 250);
</script>

<!-- 添加网站运行时间》-->
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
